import 'dart:convert';

import 'package:iidx_progress_tool/data/model/tag.dart';
import 'package:shared_preferences/shared_preferences.dart';

class TagService {
  final String _tagListKey = "tagList";
  Map<String, Tag> tagMap = {};

  /**
   * 获取所有tag
   */
  Future<List<Tag>> getTagList() async {
    if (tagMap.isEmpty) {
      await _initTags();
    }

    return tagMap.values.toList();
  }

  Future<Tag> addTag(String name) async {
    Tag tag = Tag(name);

    final perfs = await SharedPreferences.getInstance();
    List<String> tagJsonList = perfs.getStringList(_tagListKey) ?? [];
    tagJsonList.add(jsonEncode(tag));
    perfs.setStringList(_tagListKey, tagJsonList);

    return tag;
  }

  Future<void> _initTags() async {
    final perfs = await SharedPreferences.getInstance();
    List<String> tagJsonList = perfs.getStringList(_tagListKey) ?? [];

    // 如果键值存储里面没有数据的话，就加载预置数据，并写入存储
    if (tagJsonList.isEmpty) {
      List<Tag> presets = Tag.preset();
      presets.forEach((_) {
        tagMap[_.id] = _;
      });

      List<String> json = presets.map((_) {
        return jsonEncode(_);
      }).toList();
      perfs.setStringList(_tagListKey, json);
      return;
    }

    tagJsonList.forEach((_) {
      Tag tag = Tag.fromJson(jsonDecode(_) as Map<String, dynamic>);
      tagMap[tag.id] = tag;
    });
  }
}